package org.zjt.datasource;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;

import java.sql.*;

/**
 * @author <a href="juntao.zhang@qq.com">juntao.zhang</a>
 * @Description:
 * @Package org.zjt
 * @date 2018/5/9 10:29
 * @see
 */
@Slf4j
public class HikariDataSourceTest {
    public static void main(String[] args)  {



    }


    public static void executeStatement(HikariDataSource dataSource) throws SQLException{
        try(Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()){
            ResultSet resultSet = statement.executeQuery("SELECT t.* FROM ehr_user t WHERE `name` = '张军涛'");
            while (resultSet.next()){
                log.error(resultSet.getString(2));
            }
        }
    }


    /**
     * 用来调用存储过程 CallableStatement接口扩展 PreparedStatement，
     * 用来调用存储过程,它提供了对输出和输入/输出参数的支持。CallableStatement 接口还具有对 PreparedStatement 接口提供的输入参数的支持。
     * @param dataSource
     * @throws SQLException
     */
    public static void executeCallableStatement(HikariDataSource dataSource) throws SQLException{
        try(Connection connection = dataSource.getConnection();
            CallableStatement callableStatement = connection.prepareCall("{CALL pro_getBookNameById(?,?)}")){

            /**
             * 存储过程：
             *
             * DELIMITER &&
                 CREATE PROCEDURE pro_getBookNameById(IN bookId INT,OUT bN VARCHAR(20))
                 BEGIN
                 SELECT bookName INTO bn FROM t_book WHERE id=bookId;
                 END
                 &&
                 DELIMITER ;
             */
            callableStatement.setInt(1, 100);//设置第一个?的值
            callableStatement.registerOutParameter(2, Types.VARCHAR);//设置返回值类型
            callableStatement.execute();//执行sql语句
            String bookName = callableStatement.getString("bN");//获取返回值
        }
    }

    public static HikariDataSource createDataSource() {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl("jdbc:mysql://172.29.80.101:3308/uc?characterEncoding=utf-8&allowMultiQueries=true");
        config.setUsername("root");
        config.setPassword("123456");
        config.addDataSourceProperty("cachePrepStmts", "true");
        config.addDataSourceProperty("prepStmtCacheSize", "250");
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        HikariDataSource dataSource = new HikariDataSource(config);
        return dataSource;
    }
}
